package com.leyuan.base.config;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.util.Properties;
import java.util.Random;


/**
 * 验证码文本生成器
 */
@Component
public class CaptchaCreator extends DefaultKaptcha {
    Logger logger = LoggerFactory.getLogger(getClass());

    private static final String[] CNUMBERS = "0,1,2,3,4,5,6,7,8,9,10".split(",");

    private Properties properties = new Properties();

    {
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream("captcha.properties");
        try {
            properties.load(inputStream);
            super.setConfig(new Config(properties));
        } catch (IOException e) {
            logger.error("加载验证码配置失败", e);
        }
    }

    private String getMathText() {
        Random random = new SecureRandom();
        int x = random.nextInt(10);
        int y = random.nextInt(10);
        StringBuilder stringBuilder = new StringBuilder();

        int randomOperands = random.nextInt(3);
        int result;

        if (randomOperands == 0) {
            result = x * y;
            mathAppend(stringBuilder, CNUMBERS[x], CNUMBERS[y], '*');
        } else if (randomOperands == 1) {
            if (y != 0 && x % y == 0) {
                result = x / y;
                mathAppend(stringBuilder, CNUMBERS[x], CNUMBERS[y], '/');
            } else {
                result = x + y;
                mathAppend(stringBuilder, CNUMBERS[x], CNUMBERS[y], '+');
            }
        } else {
            if (x >= y) {
                result = x - y;
                mathAppend(stringBuilder, CNUMBERS[x], CNUMBERS[y], '-');
            } else {
                result = y - x;
                mathAppend(stringBuilder, CNUMBERS[y], CNUMBERS[x], '-');
            }
        }
        stringBuilder.append("=?#").append(result);
        return stringBuilder.toString();
    }

    /**/
    public Captcha createMathImage() {
        String[] array = getMathText().split("#");
        return new Captcha(array[1], super.createImage(array[0]));
    }

    /**/
    public Captcha createTextImage() {
        String text = createText();
        return new Captcha(text, super.createImage(text));
    }

    private void mathAppend(StringBuilder stringBuilder, String x, String y, char symbol) {
        stringBuilder.append(x);
        stringBuilder.append(symbol);
        stringBuilder.append(y);
    }

}
